import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Button, 
  Space, 
  Typography, 
  Select, 
  Tooltip,
  Card,
  Row,
  Col,
  Tag
} from 'antd';
import {
  ShareAltOutlined,
  EditOutlined,
  DownloadOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  FullscreenOutlined
} from '@ant-design/icons';

import GraphVisualizationHub from '../../../../components/GraphVisualizationHub';

const { Text, Title } = Typography;
const { Option } = Select;

const GraphPreviewModal = ({ 
  visible, 
  onCancel, 
  graphData, 
  onEdit, 
  onShare,
  graphTypeDefinitions,
  graphLayoutDefinitions 
}) => {
  const [graphType, setGraphType] = useState('knowledge');
  const [graphStyle, setGraphStyle] = useState('force');
  const [zoomLevel, setZoomLevel] = useState(1);

  // 使用传入的布局定义，如果没有则使用默认定义
  const defaultLayoutDefinitions = {
    force: { name: '力导向布局', description: '基于物理模拟的节点自然分布' },
    circular: { name: '环形布局', description: '节点均匀分布在圆周上' },
    hierarchical: { name: '层次布局', description: '按层级关系从上到下排列' },
    grid: { name: '网格布局', description: '节点均匀分布在网格中' },
    radial: { name: '辐射布局', description: '从中心向外辐射的树状结构' },
    tree: { name: '树形布局', description: '自上而下或自左向右的树状结构' }
  };
  const layoutDefinitions = graphLayoutDefinitions || defaultLayoutDefinitions;

  useEffect(() => {
    if (graphData) {
      try {
        setGraphType(graphData.type || 'knowledge');
        setGraphStyle(graphData.layout || 'force');
        setZoomLevel(1); // 重置缩放级别
      } catch (error) {
        console.error("处理图谱数据时出错:", error);
      }
    }
  }, [graphData]);

  // 处理节点点击 - 预览模式只显示信息，不编辑
  const handleNodeClick = (node) => {
    console.log('预览模式 - 查看节点:', node);
    // 可以显示节点详情，但不允许编辑
  };

  // 处理关系点击 - 预览模式只显示信息，不编辑
  const handleEdgeClick = (edge) => {
    console.log('预览模式 - 查看关系:', edge);
    // 可以显示关系详情，但不允许编辑
  };

  const handleExport = () => {
    console.log('导出图谱');
    // 实现导出功能
  };

  const handleZoomIn = () => {
    setZoomLevel(prev => Math.min(prev + 0.2, 3));
  };

  const handleZoomOut = () => {
    setZoomLevel(prev => Math.max(prev - 0.2, 0.5));
  };

  const handleReset = () => {
    setZoomLevel(1);
  };

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>{graphData?.name} - 预览</span>
          <Space>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              只读模式
            </Text>
          </Space>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      width={1000}
      footer={[
        <Button key="edit" type="primary" onClick={() => onEdit(graphData)}>
          编辑图谱
        </Button>,
        <Button key="share" icon={<ShareAltOutlined />} onClick={() => onShare(graphData)}>
          分享
        </Button>,
        <Button key="export" icon={<DownloadOutlined />} onClick={handleExport}>
          导出
        </Button>,
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>
      ]}
      styles={{body:{ padding: '16px' }}}
    >
      {graphData && (
        <div>
          {/* 图谱基本信息 */}
          <Card size="small" style={{ marginBottom: '16px' }}>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <div>
                  <Title level={5} style={{ margin: 0, marginBottom: '4px' }}>
                    {graphData.name}
                  </Title>
                  <Text type="secondary" style={{ fontSize: '13px' }}>
                    {graphData.description}
                  </Text>
                </div>
              </Col>
              <Col>
                <Space size="large">
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1677ff' }}>
                      {graphData?.nodes?.length || 0}
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>实体</Text>
                  </div>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#52c41a' }}>
                      {graphData?.edges?.length || 0}
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>关系</Text>
                  </div>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#fa8c16' }}>
                      {graphData.progress}%
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>完成度</Text>
                  </div>
                </Space>
              </Col>
            </Row>
          </Card>
          
          {/* 控制面板 */}
          <Card size="small" style={{ marginBottom: '16px' }}>
            <Row justify="space-between" align="middle">
              <Col>
                <Space>
                  <span style={{ fontSize: '14px', fontWeight: 'bold' }}>布局样式:</span>
                  <Select
                    value={graphStyle}
                    onChange={setGraphStyle}
                    size="small"
                    style={{ width: 120 }}
                  >
                    {Object.entries(layoutDefinitions).map(([key, layout]) => (
                      <Option key={key} value={key} title={layout.description}>
                        {layout.name}
                      </Option>
                    ))}
                  </Select>
                </Space>
              </Col>
              <Col>
                <Space>
                  <Tooltip title="放大">
                    <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
                  </Tooltip>
                  <Tooltip title="缩小">
                    <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
                  </Tooltip>
                  <Tooltip title="重置">
                    <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
                  </Tooltip>
                  <Tooltip title="全屏">
                    <Button size="small" icon={<FullscreenOutlined />} />
                  </Tooltip>
                  <Text type="secondary" style={{ fontSize: '12px', marginLeft: '8px' }}>
                    缩放: {Math.round(zoomLevel * 100)}%
                  </Text>
                </Space>
              </Col>
            </Row>
          </Card>
          
          {/* 图谱可视化区域 */}
          <div style={{ 
            border: '1px solid #d9d9d9', 
            borderRadius: '6px',
            background: '#fff',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <GraphVisualizationHub
              nodes={graphData?.nodes || []}
              edges={graphData?.edges || []}
              graphType={graphData?.type || 'knowledge'} // 使用type而不是status
              layout={graphStyle}
              onLayoutChange={setGraphStyle}
              onNodeClick={handleNodeClick}
              onEdgeClick={handleEdgeClick}
              editable={false} // 预览模式不可编辑
              height={500}
              zoom={zoomLevel}
              errorHandler={(error) => {
                console.error("图谱预览渲染错误:", error);
              }}
            />
            
            {/* 预览模式提示 */}
            <div style={{
              position: 'absolute',
              top: '8px',
              left: '8px',
              background: 'rgba(0, 0, 0, 0.6)',
              color: '#fff',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px'
            }}>
              预览模式 - 只读
            </div>
          </div>
          
          {/* 图谱标签和创建信息 */}
          <div style={{ 
            marginTop: '16px', 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center',
            padding: '12px',
            background: '#fafafa',
            borderRadius: '6px'
          }}>
            <Space>
              <Text strong>标签:</Text>
              {graphData.tags?.map(tag => (
                <Tag key={tag} color="blue">
                  {tag}
                </Tag>
              ))}
            </Space>
            <Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                创建者: {graphData.creator}
              </Text>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                创建时间: {graphData.createTime}
              </Text>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                查看次数: {graphData.viewCount}
              </Text>
            </Space>
          </div>
        </div>
      )}
    </Modal>
  );
};

export default GraphPreviewModal;